//
//  PopularizeDetailsViewController.m
//  GreenEarnings
//
//  Created by chirui on 2018/4/18.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "PopularizeDetailsViewController.h"
#import "PopuDetailsTableViewCell.h"

@interface PopularizeDetailsViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    NSMutableArray * _dataArray;
    int _totailPage;
    int _page;
    UITableView * _tableView;
    NSDictionary * userDic;
    
    //时间选择
    UIView * dataPickBgView ; // 背景颜色
    UIDatePicker * datePicker;
    NSString * timeType;
    
    UIButton * starTime;
    UIButton * endTime;
    
    NSString * starTimeStr;
    NSString * endTimeStr;
}

@end

@implementation PopularizeDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 1;
    _dataArray = @[].mutableCopy;
    
    TitleView(@"充值详情");
    [self creatTableView];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    
    starTimeStr = str;
    endTimeStr = str;
    
    [self getMessageListData];
    
    dataPickBgView =[[UIView alloc]initWithFrame:CGRectMake(0,  HEIGHT -200-94, WIDTH, 230)];
    dataPickBgView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    dataPickBgView.hidden=YES;
    datePicker =[[UIDatePicker alloc]initWithFrame:CGRectMake(0,30, WIDTH, 200)];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.backgroundColor =[UIColor groupTableViewBackgroundColor];
    [datePicker addTarget:self action:@selector(chooseDate:) forControlEvents:UIControlEventValueChanged];
        NSDate * date =[[NSDate alloc]init];
        datePicker.maximumDate = date;
    
    [dataPickBgView addSubview:datePicker];
    
    UIButton * cannelBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    cannelBtn.frame = CGRectMake(0, 0, 80, 30);
    [cannelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cannelBtn addTarget:self action:@selector(cannelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [dataPickBgView addSubview:cannelBtn];
    
    UIButton * sureBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    sureBtn.frame = CGRectMake(WIDTH - 80, 0, 80, 30);
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(chooseTimeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [dataPickBgView addSubview:sureBtn];
    
    
    [self.view addSubview:dataPickBgView];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)cannelBtnClick:(UIButton *)btn {
    
    dataPickBgView.hidden =YES;
}

-(void)chooseTimeBtnClick:(UIButton *)btn {
    
    dataPickBgView.hidden =YES;
    _page =1;
    [self getMessageListData];
}

-(void)creatTableView {
    
    _tableView  =[[UITableView alloc]initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT-SH_TopHeight)
                                             style:UITableViewStyleGrouped];
    _tableView.dataSource=self;
    _tableView.delegate =self;
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView =view;
    
    [_tableView registerNib:[UINib nibWithNibName:@"PopuDetailsTableViewCell" bundle:nil] forCellReuseIdentifier:[PopuDetailsTableViewCell reuseIdentifier]];
    
    [self.view addSubview:_tableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataArray.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPat{
    
    return 60;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return  200;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    NSDictionary * dic = _dataArray[indexPath.row];
    PopuDetailsTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[PopuDetailsTableViewCell reuseIdentifier]];
    
    cell.timeLabel.text = dic[@"create_time"];
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",dic[@"order_price"]];
    return cell;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //    NSDictionary * dic = _dataArray[indexPath.row];
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView * topView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    topView.backgroundColor =[UIColor whiteColor];
    
    UIImageView * bgImage = [[UIImageView alloc]initWithFrame:CGRectMake(20, 30, 70, 70)];

    [bgImage sd_setImageWithURL:ImageUrl(self.dataDic[@"header"]) placeholderImage:ImageName(@"img_user_initial _head")];
    bgImage.layer.cornerRadius = 35.f;
    bgImage.layer.masksToBounds = YES;
    [topView addSubview:bgImage];
    
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 55, 100, 30)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = self.dataDic[@"nickname"];
    titleLabel.font = [UIFont systemFontOfSize:15];
    [topView addSubview:titleLabel];
    
    UILabel * allLabel = [[UILabel alloc]initWithFrame:CGRectMake(200 , 55, WIDTH-210, 20)];
    allLabel.textAlignment = NSTextAlignmentRight;
    allLabel.textColor = NavBackColor;
    allLabel.text = @"￥0.00";
    if (userDic) {
        allLabel.text = [NSString stringWithFormat:@"￥%@",userDic[@"sum"]];
    }
    allLabel.font = [UIFont systemFontOfSize:17];
    [topView addSubview:allLabel];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 140, WIDTH, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [topView addSubview:lineView];
    
    UIView * lineView_1 = [[UIView alloc]initWithFrame:CGRectMake(0, 190, WIDTH, 10)];
    lineView_1.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [topView addSubview:lineView_1];
   
    
    starTime = [UIButton buttonWithType:UIButtonTypeCustom];
    starTime.frame = CGRectMake(0, 141, WIDTH/2-15, 49);
    [starTime setTitle:starTimeStr forState:UIControlStateNormal];
    [starTime setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [starTime addTarget:self action:@selector(statTimeClick:) forControlEvents:UIControlEventTouchUpInside];
      starTime.imageEdgeInsets = UIEdgeInsetsMake(20,WIDTH/2-40,20,20);
    [starTime setImage:ImageName(@"icon_class") forState:UIControlStateNormal];
    [topView addSubview:starTime];
    
    UILabel * Label = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2-15, 141, 30, 49)];
    Label.textAlignment = NSTextAlignmentCenter;
    Label.text = @"到";
    Label.font = [UIFont systemFontOfSize:15];
    [topView addSubview:Label];
    
    endTime = [UIButton buttonWithType:UIButtonTypeCustom];
    endTime.frame = CGRectMake(WIDTH/2+15, 141, WIDTH/2-30, 49);
    [endTime setTitle:endTimeStr forState:UIControlStateNormal];
    [endTime setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [endTime addTarget:self action:@selector(endTimeClick:) forControlEvents:UIControlEventTouchUpInside];
    endTime.imageEdgeInsets = UIEdgeInsetsMake(20,WIDTH/2-40,20,20);
    [endTime setImage:ImageName(@"icon_class") forState:UIControlStateNormal];
    [topView addSubview:endTime];
   
    return topView;
}

-(void)statTimeClick:(UIButton *)btn{
    timeType = @"stat";
   dataPickBgView.hidden = NO;
}

-(void)endTimeClick:(UIButton *)btn{
    timeType = @"end";
   dataPickBgView.hidden = NO;
}

-(void)chooseDate:(UIDatePicker *)picker{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    
    if ([timeType isEqualToString:@"stat"]) {
        starTimeStr = [formatter stringFromDate:picker.date] ;
        [starTime setTitle:starTimeStr forState:UIControlStateNormal];
    }
    if ([timeType isEqualToString:@"end"]) {
         endTimeStr = [formatter stringFromDate:picker.date] ;
        if ([SHJudgeTools compareDate:endTimeStr withDate:starTimeStr] == 1) {
            SHuiMBhudTextTimeStr(@"截止日期不能小于开始日期");
            endTimeStr = [formatter stringFromDate:[NSDate date]];
        }else {
          [endTime setTitle:[formatter stringFromDate:picker.date] forState:UIControlStateNormal];
        }
    }
}

-(void)getMessageListData{
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];

            return ;
        }
    }
    NSDictionary * dic = @{@"token":USER_DEFAULTGet(@"token"),
                           @"mid":USER_DEFAULTGet(@"mid"),
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"perpage":@"10",
                           @"member_mid":self.dataDic[@"mid"],
                           @"start_time":starTimeStr,
                           @"end_time":endTimeStr
                           };

    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_myLowerDetails_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [responseObject[@"datas"][@"total_page"] intValue];
            userDic = responseObject[@"datas"];
            if (_page==1) {

                if (_dataArray) {

                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {

                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {

                        [_dataArray addObject:dic];
                    }
                }
            }else {

                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {

                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {

                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{

                if (_dataArray.count>0) {

                    if (_dataArray.count<10) {

                        _tableView.mj_footer.hidden = YES;
                    }else {
                        _tableView.mj_footer.hidden = NO;
                    }
                }else {
                    _tableView.mj_footer.hidden = YES;

                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
            });
        }else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];

}


@end
